﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FastDFS.Client;
using FastDFS.WinForm.Models;

namespace FastDFS.WinForm.Forms
{
    public partial class ApiForm : Form
    {

        private List<IPEndPoint> trackerIPs;
        private IPEndPoint endPoint;
        private StorageNode node;
        private Stopwatch sw = new Stopwatch();

        private FDFSTableDataContext fdfsContext=LocalDataContextFactory.getFDFSDataContext();

        public ApiForm()
        {
            InitializeComponent();
            
            trackerIPs = new List<IPEndPoint>();
            endPoint = new IPEndPoint(IPAddress.Parse(AppConfig.DFS_TRACKER_HOST), 22122);
            trackerIPs.Add(endPoint);

            tbAppendGroupName.Text = tbDeleteGroupName.Text = tbUploadGroupName.Text = "group1";

        }

        protected void initDFS(params string[] groupNames)
        {

            
            ConnectionManager.Initialize(trackerIPs);
            if (groupNames.Length > 0&&!string.IsNullOrWhiteSpace(groupNames[0]))
            {
                node = FastDFSClient.GetStorageNode(groupNames[0]);
            }
            else
            {
                node = FastDFSClient.GetStorageNode();
            }
        }

      
        private void updateInfo(string pattern, params object[] vals)
        {
            toolStripStatusLabel1.Text = string.Format(pattern, vals);
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            DialogResult dre = ofdUpload.ShowDialog();
            if (dre != DialogResult.OK)
            {
                return;
                updateInfo("以选中个{0}文件，请点击上传", ofdUpload.FileNames.Length);
            }
            else
            {
                dre = MessageBox.Show("已选中" + ofdUpload.FileNames.Length + " 个文件,是否马上上传?", "上传文件", MessageBoxButtons.OKCancel);
                if (dre != DialogResult.OK) return;
            }



            initDFS(tbUploadGroupName.Text);
            updateInfo("upload starting "+tbUploadGroupName.Text+"...");
            DateTime start = DateTime.Now;
            string msg = "file list \n";
            ofdUpload.FileNames.AsParallel().ForAll(f =>
            {
                string masterfdfsname = FastDFSClient.UploadFile(node, f)[0], ext = Path.GetExtension(f);

                FDFSFileInfo fileInfo = FastDFSClient.GetFileInfo(node, masterfdfsname);

                //string fileName = FastDFSClient.UploadAppenderFile(node, content, "mdb");
                //string key = FastDFSClient.UploadFile(node, content, ext);
                msg += string.Format("file:{0}\nkey:{1}\n\n", f, masterfdfsname);
                tbDownloadKey.Text = masterfdfsname;

                attachment attachment = new attachment
                {
                    fdfs_key = masterfdfsname
                    ,
                    fdfs_upload_at = DateTime.Now
                    ,
                    file_name = f
                    ,
                    file_ext = ext
                    ,
                    file_size = (int)fileInfo.FileSize

                };
               // fdfsContext.attachments.InsertOnSubmit(attachment);
               // fdfsContext.SubmitChanges();
                string url = string.Format("http://{0}:{1}/{2}/{3}"
                , node.EndPoint.Address
                , 80
                , tbUploadGroupName.Text
                , masterfdfsname
                );
                linkDonwloadMasterFile.Text = url;
            });

            DateTime end = DateTime.Now;
            TimeSpan consume = ((TimeSpan)(end - start));
            double consumeSeconds = Math.Ceiling(consume.TotalSeconds);
            updateInfo("upload finish....{0}", consumeSeconds);
            MessageBox.Show(msg);

            

        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            string key = tbDownloadKey.Text;

            if (string.IsNullOrWhiteSpace(key))
            {
                MessageBox.Show("key can't be blank");
                return;
            }

            sfdDownload.FileName = key;
            sfdDownload.DefaultExt=Path.GetExtension(key);
            DialogResult dre = sfdDownload.ShowDialog();
            if (dre != DialogResult.OK) return;
            initDFS();
            
            int eff= FastDFSClient.DowloadAndSaveFile(node, key, sfdDownload.FileName);
            
            MessageBox.Show(string.Format("file {0} success save to {1}", key, sfdDownload.FileName));
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            initDFS();
            string key = tbDownloadKey.Text;
            FDFSFileInfo fi= FastDFSClient.GetFileInfo(node,key);
            lbQueryResult.Text = string.Format("CreateTime:{0}\n FileSize:{1}\nCrc32:{2}"
                ,fi.CreateTime.ToString("G")
                ,fi.FileSize
                ,fi.Crc32
                );
        }

        private void lbQueryResult_Click(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void btnAppend_Click(object sender, EventArgs e)
        {
            DialogResult dre = ofdAppend.ShowDialog();
            if (dre != DialogResult.OK)
            {
                return;
                updateInfo("以选中个{0}文件，请点击上传", ofdUpload.FileNames.Length);
            }
            else
            {
                dre = MessageBox.Show("已选中" + ofdUpload.FileNames.Length + " 个文件,是否马上追加?", "追加文件", MessageBoxButtons.OKCancel);
                if (dre != DialogResult.OK) return;
            }



            initDFS(tbUploadGroupName.Text);
            updateInfo("append starting " + tbUploadGroupName.Text + "...");
            DateTime start = DateTime.Now;
            string msg = "file list \n";
            ofdUpload.FileNames.AsParallel().ForAll(f =>
            {
                string key="",name = Path.GetFileName(f), ext = Path.GetExtension(f);
                byte[] content = null;
                using (FileStream streamUpload = new FileStream(f, FileMode.Open))
                {
                    //key=FastDFSClient.
                }


                //string fileName = FastDFSClient.UploadAppenderFile(node, content, "mdb");
                //string key = FastDFSClient.UploadFile(node, content, ext);
                msg += string.Format("file:{0}\nkey:{1}\n\n", name, key);
                tbDownloadKey.Text = key;

                attachment attachment = new attachment
                {
                    fdfs_key = key
                    ,
                    fdfs_upload_at = DateTime.Now
                    ,
                    file_name = name
                    ,
                    file_ext = ext
                    ,
                    file_size = content.Length

                };
                // fdfsContext.attachments.InsertOnSubmit(attachment);
                // fdfsContext.SubmitChanges();
            });

            DateTime end = DateTime.Now;
            TimeSpan consume = ((TimeSpan)(end - start));
            double consumeSeconds = Math.Ceiling(consume.TotalSeconds);
            updateInfo("upload finish....{0}", consumeSeconds);
            MessageBox.Show(msg);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
           
            DialogResult dre= MessageBox.Show("确认要删除吗?", "", MessageBoxButtons.YesNo);
            if (dre != DialogResult.Yes)return;
            initDFS();
            FastDFSClient.RemoveFile(tbDeleteGroupName.Text,tbDeleteFDFSName.Text);
        }

        private void btnUploadAppend_Click(object sender, EventArgs e)
        {

        }

        private void linkDownload_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            LinkLabel ll = (LinkLabel)sender;
            System.Diagnostics.Process.Start(ll.Text);
        }


    }
}
